﻿-- Author      : Kurapica

--[[
	Advance Frame for TabGroup
--]]
do
	IGAS:NewAddon("IGAS_Studio")
	local _Widget = IGAS.GUI.Widget.TabGroup

	-- From
	local form = CreateFrame(Widget.AdvanceForm, "IGAS_Studio_Advance_TabGroup", coreF)
	form.Caption = L["Advance for TabGroup"]
	form.btnUp.Enabled = true
	form.btnDown.Enabled = true

	local lst = form.List
	local dtg = form.DataGrid
	local _Frame

	-- Scripts
	local function addTabPage(name)
		if name and strtrim(name) ~= "" then
			name = strtrim(name)

			lst:SetItem(name, name)
		end
	end

	function form:OnAddClick()
		return IGAS:MsgBox(L["Please input the label of the new tab"], "ic", addTabPage)
	end

	function form:OnRemoveClick()
		if lst:GetSelectedItemIndex() > 0 then
			lst:RemoveItem(lst:GetSelectedItemValue())
		end
	end

	function form:OnUpClick()
		local i = lst:GetSelectedItemIndex()
		if i and i > 1 then
			lst.Keys[i], lst.Keys[i-1] = lst.Keys[i-1], lst.Keys[i]
			lst.Items[i], lst.Items[i-1] = lst.Items[i-1], lst.Items[i]
			lst:SelectItemByIndex(i - 1)
			lst:Refresh()
		end
	end

	function form:OnDownClick()
		local i = lst:GetSelectedItemIndex()
		if i and i < #self.Keys then
			lst.Keys[i], lst.Keys[i+1] = lst.Keys[i+1], lst.Keys[i]
			lst.Items[i], lst.Items[i+1] = lst.Items[i+1], lst.Items[i]
			lst:SelectItemByIndex(i + 1)
			lst:Refresh()
		end
	end

	function form:OnOkayClick()
		for i, name in pairs(lst.Keys) do
			if _Frame:GetTabByIndex(i) then
				_Frame:GetTabByIndex(i).Text = name
			else
				_Frame:AddTab(name)
			end
		end

		for i = _Frame.TabNum, #lst.Keys + 1, -1 do
			_Frame:RemoveTabByIndex(i)
		end

		self.Visible = false

		self:FireEvent("IGAS_STUDIO_FRAME_ADVANCED", _Frame)

		lst:Clear()
		_Frame = nil
	end

	-- start advance setting for the frame
	function form:SetFrame(frame)
		local text

		-- Clear
		lst:Clear()
		_Frame = frame

		-- Add TabPages
		for i = 1, frame.TabNum do
			text = frame:GetTabByIndex(i).Text
			lst:SetItem(text, text)
		end
	end

	-- return the frame's special container.
	function form:GetContainerList(frame)
		local rList = {}
		local tab

		if frame and frame:IsObjectType(_Widget) then
			for i = 1, frame.TabNum do
				tab = frame:GetTabByIndex(i)
				rList[tab.Container] = "TabContainer_"..i
			end
		end

		return rList
	end

	-- return the frame's special build-code.Just return the containers.Others would be generated automatically
	function form:Serialize(frame, name, _FrameInfoList)
		local rList = {}

		if frame and frame:IsObjectType(_Widget) then
			for i = 1, frame.TabNum do
				tab = frame:GetTabByIndex(i)
				if _FrameInfoList[tab.Container] then
					tinsert(rList, "".._FrameInfoList[tab.Container].Name.." = "..name..":AddTab(L[\""..tab.Text.."\"]).Container")
				end
			end
		end

		return table.concat(rList, "\n")
	end

	-- Register
	Advance[_Widget] = form
end